<?php
require('SendSms.php');

$goods = $_POST['goods'];
$name = $_POST['name'];
$uid = $_POST['uid'];
$phone = $_POST['phone'];
$sf = $_POST['sf'];
$city = $_POST['city'];
$xian = $_POST['xian'];
$dizhi = $_POST['dizhi'];
$oderid = $_POST['oderid'];
$time = $_POST['time'];
$channel = $_POST['channel'];
$price = $_POST['price'];
$thirdphone = $_POST['thirdphone'];
$beizhu = "已经提交运营商审核";

include_once("../untils/conn.php");

// 执行查询
$sql = "SELECT * FROM cityCode WHERE postProvinceName = '$sf' AND postCityName = '$city' AND postDistrictName = '$xian'";
$result = $con->query($sql);

// 检查是否有匹配的结果
if ($result->num_rows > 0) {
    // 获取查询结果的第一行数据
    $row = $result->fetch_assoc();
    
    // 提取需要的字段值并存储为变量
    $postProvinceCode = $row['postProvinceCode'];
    $postCityCode = $row['postCityCode'];
    $postDistrictCode = $row['postDistrictCode'];
} else {
    // echo "没有对应代码~，请联系管理员更新~";
}
// 执行查询
$sqlconfig = "SELECT * FROM config_api WHERE groups = 'gantanhao'";
$result = $con->query($sqlconfig);

// 检查是否有匹配的结果
if ($result->num_rows > 0) {
    // 获取查询结果的第一行数据
    $row = $result->fetch_assoc();
    
    // 提取需要的字段值并存储为变量
      $userid = $row['userid'];
      $token  = $row['token'];
} else {
    // echo "没有配置接口~，请联系管理员配置~";
     $response = array('status' => -5, 'msg' => '该地区没有符合的城市编码！');
     echo json_encode($response);
}

if ($con) {
    mysqli_query($con, "set names utf8");

    // 判断是否有name，uid，phone，dizhi这四项信息，如果有任何一项为空，则返回错误信息
    if (empty($name) || empty($uid) || empty($phone) || empty($dizhi)) {
        $response = array('status' => -1, 'msg' => '信息不完整，请重新输入');
        echo json_encode($response);
        return;
    }

    // 判断订单是否已经提交过
    session_start();
    if (isset($_SESSION['order_id']) && $_SESSION['order_id'] == $oderid) {
        $response = array('status' => 1, 'msg' => '订单已经提交过了');
        echo json_encode($response);
        return;
    }

    $data_query = mysqli_query($con, "select * from oder where uid='$uid'");
    $count = mysqli_num_rows($data_query);

        if ($count > 10) {
            // 用户已经申请过了，返回状态码1和提示信息
            $response = array('status' => 1, 'msg' => '您申请的订单已超限，请联系客服');
            echo json_encode($response);
        } else {
            // 判断$channel变量是否为空，如果为空则将其赋值为null
            if(empty($channel)){
                $channel = 0;
            }
            $data_insert = mysqli_query($con, "insert into oder(goods,name,uid,phone,sf,city,xian,dizhi,oderid,time,price,channel,thirdphone) values('$goods','$name','$uid','$phone','$sf','$city','$xian','$dizhi','$oderid','$time','$price','$channel','$thirdphone')");
        
            if ($data_insert) {
                $sql = "SELECT haokaid FROM list WHERE name='$goods'";
                $res = mysqli_query($con, $sql);
                if(mysqli_num_rows($res) > 0){
                    $row = mysqli_fetch_assoc($res);
                    $haokaid = $row['haokaid'];
                }

                   if ($haokaid === null || $haokaid === '') {
                    // $haokaid为null或空，执行特定的代码
                    $response = array('status' => 0, 'msg' => '申请成功');
                    echo json_encode($response);
                    //发送短信通知
                    sendSms($appId, $appKey, $phoneNumber, $templateId, $smsSign);
                     } else {
                   
        
                   function buildSign($param, $token)
                    {
                        $str = 'share_id=' . $param['share_id'] . '&sku=' . $param['sku'] . '&source_id=' . $param['source_id'] . $token;
                        $sign = md5($str);
                        return $sign;
                    }
                    
                    // 构造请求参数
                    $params = array(
                        'sku' => $haokaid,
                        'share_id' => $userid,
                        'source_id' => $oderid,
                        'id_name' => $name,
                        'id_num' => $uid,
                        'mobile' => $phone,
                        'name' => $name,
                        'province' => $sf,
                        'city' => $city,
                        'district' => $xian,
                        'address' => $dizhi,
                    );
                    
                    // 计算签名
                  $sign = buildSign($params, $token);
                   
                    // 添加签名到请求参数
                    $params['sign'] = $sign;
                    
                    // 发送请求
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, 'http://notify.91haoka.cn/api/plan-market/order/purchase');
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $response = curl_exec($ch);
                    curl_close($ch);
                    
                    // echo "data：" . $response . "\n";
                    // exit;

                   
                    // 解析响应数据
                    $result = json_decode($response, true);
                    
                    if ($result) {
                        if ($result['data']['status'] == 120) {
                            // 更新订单状态
                            $update_sql = "UPDATE oder SET status=1, beizhu='$beizhu' WHERE oderid='$oderid'";
                            $update_query = mysqli_query($con, $update_sql);
                    
                            if ($update_query) {
                                // 更新成功，返回状态码0和提示信息
                                $response = array('status' => 0, 'msg' => '申请成功');
                                echo json_encode($response);
                                // 将订单号写入session
                                $_SESSION['order_id'] = $oderid;
                    
                                //发送短信通知
                                sendSms($appId, $appKey, $phoneNumber, $templateId, $smsSign);
                            } else {
                                // 更新失败，返回状态码-2和提示信息
                                $response = array('status' => -2, 'msg' => '更新订单状态失败');
                                echo json_encode($response);
                            }
                        } else {
                            // 下单失败，返回接口返回的错误信息
                            $response = array('status' => $result['code'], 'msg' => $result['message']);
                            echo json_encode($response);
                        }
                    } else {
                        // 解析失败，返回错误信息
                        $response = array('status' => -1, 'msg' => '解析响应数据失败');
                        echo json_encode($response);
                    }

                }
            } else {
                // 信息不全，返回状态码-1和提示信息
                $response = array('status' => -1, 'msg' => '哦豁，又出错了，找客服吧~');
                echo json_encode($response);
            }
        }
}


?>
